/*
 * @Author: WuFeng <763467339@qq.com>
 * @Date: 2022-03-22 12:12:49
 * @LastEditTime: 2022-03-22 12:29:24
 * @LastEditors: WuFeng <763467339@qq.com>
 * @Description: 多语言控制
 * @FilePath: \vue3-element-plus-web\src\language\index.js
 * @Copyright 版权声明
 */
import { createI18n } from 'vue-i18n/index'
import { getLanguageType } from '@/language/handleLanguage'
import 'dayjs/locale/zh-cn'
import zhCN from './zh-cn'
import zhTW from './zh-tw'
import en from './en'
const messages = {
  'zh-cn': zhCN,
  'zh-tw': zhTW,
  'en': en
}

// Gets the current locale
// getLanguage 函数 判断当前localStorage是否已有选择过语言如果没有则获取当前浏览器的语言；
export function getLanguage() {
  // Use the language of choice
  // const chooselang = localStorage.getItem('locale')
  const chooselang = getLanguageType()
  if (chooselang) return chooselang
  // if not shoose language
  const lang = (navigator.language || navigator.browserLanguage).toLowerCase()
  const locales = Object.keys(messages)
  return locales.includes(lang) ? lang : 'zh-cn'
}

const i18n = createI18n({
  locale: getLanguage(),
  fallbackLocale: 'en',
  global: true,
  messages
})

// 封装 $t 函数并导出用在js文件中console
export function $t(args) {
  return i18n.global.tc(args)
}

export default (app) => {
  app.use(i18n)
}
